import classnamesFn from 'classnames';
import React, { useEffect, useRef } from 'react';
import type { YmResizeObserverProps } from './interface';
import { observe, unobserve } from './utils/observerUtil';

const YmResizeObserver: React.FC<YmResizeObserverProps> = (props) => {
  const {
    children,
    onResize,
    prefixCls = 'ym-resize',
    rootClassName,
    rootStyle,
    isFullParent,
  } = props;
  const resizeRef = useRef<HTMLDivElement>(null);

  const sizeRef = useRef({
    width: -1,
    height: -1,
    offsetWidth: -1,
    offsetHeight: -1,
  });

  // Handler
  const onInternalResize = (target: HTMLElement) => {
    const { width, height } = target.getBoundingClientRect();
    const { offsetWidth, offsetHeight } = target;

    /**
     * Resize observer trigger when content size changed.
     * In most case we just care about element size,
     * let's use `boundary` instead of `contentRect` here to avoid shaking.
     */
    const fixedWidth = Math.floor(width);
    const fixedHeight = Math.floor(height);

    if (
      sizeRef.current.width !== fixedWidth ||
      sizeRef.current.height !== fixedHeight ||
      sizeRef.current.offsetWidth !== offsetWidth ||
      sizeRef.current.offsetHeight !== offsetHeight
    ) {
      const size = {
        width: fixedWidth,
        height: fixedHeight,
        offsetWidth,
        offsetHeight,
      };
      sizeRef.current = size;

      const sizeInfo = {
        ...size,
        offsetWidth,
        offsetHeight,
      };

      onResize?.(sizeInfo, target);
    }
  };

  useEffect(() => {
    if (!resizeRef.current) return;
    if (isFullParent) {
      // const resizeDom = resizeRef.current;
      // if (
      //   resizeDom &&
      //   resizeDom.parentNode &&
      //   resizeDom.parentNode.ownerDocument &&   //ownerDocument:返回当前节点的根元素（document 对象）
      //   resizeDom.parentNode.ownerDocument.defaultView && // document.defaultView === window (window对象)
      //   resizeDom.parentNode instanceof resizeDom.parentNode.ownerDocument.defaultView.HTMLElement
      // ) {
      //   const elementStyle = window.getComputedStyle(resizeDom.parentNode);
      //   if (elementStyle && elementStyle.position === 'static') {
      //     // resizeDom.parentNode.style.position = 'relative';
      //   }
      // }
    }

    observe(resizeRef.current, onInternalResize);
    return () => {
      unobserve(resizeRef.current!, onInternalResize);
    };
  }, []);

  return (
    <div
      ref={resizeRef}
      className={classnamesFn(prefixCls, rootClassName, {
        [`${prefixCls}-isfull`]: isFullParent,
      })}
      style={rootStyle}
    >
      {children}
    </div>
  );
};

export default YmResizeObserver;
